package org.singledog.form.builder;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;

@Slf4j
public class SpringContextHolder {

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        Assert.notNull(context, "Spring context can not be null !");
        applicationContext = context;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 首先按照 bean name 查找， 找不到则按照type查找 都找不到则返回null
     * @param type
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> type, String beanName) {
        Assert.notNull(applicationContext, "Spring context is null !");
        T t = null;

        try {
            t = applicationContext.getBean(beanName, type);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (t != null) {
            return t;
        }

        try {
            t = applicationContext.getBean(type);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return t;
    }

}
